﻿#include "TlvCmdTask.h"
#include "services/tlv/Com/TlvThreadCom.h"

#include <QTimer>
#include <QEventLoop>
#include <QDebug>

TlvCmdTask::TlvCmdTask(QObject *parent)
    : ITask(parent)
    , m_isIIC(false)
    , m_runCnt(1)
    , m_requestStop(false)
{
    connect(TlvThreadCom::instance(), &TlvThreadCom::errorOccurred, this, &TlvCmdTask::errorOccurred);
}

TlvCmdTask::~TlvCmdTask()
{

}

void TlvCmdTask::stop()
{
    m_runCnt = 0;
    m_requestStop = true;
    ITask::stop();
}

void TlvCmdTask::setRunIICCmds(const QList<IICSend_t>& cmds)
{
    m_iicCmds = cmds;
    m_isIIC = true;
}

void TlvCmdTask::setRunTlvCmds(const QList<TlvSend_t>& cmds)
{
    m_tlvCmds = cmds;
    m_isIIC = false;
}

void TlvCmdTask::setRunCnt(int cnt)
{
    m_runCnt = cnt;
}

TlvCmdTask *TlvCmdTask::instance()
{
    static TlvCmdTask* inst = nullptr;
    if (!inst) {
        inst = new TlvCmdTask();
    }
    return inst;
}

void TlvCmdTask::runIIC()
{
    int i = 0;
    emit hasDone(0, 0);
    for (const IICSend_t& iicCmd : m_iicCmds) {

        auto res = TlvThreadCom::instance()->syncWrite(iicCmd.iic);
        if (res.isEmpty()) {  // 超时了
            stop();
        } else {
            emit hasDone(i, (int)(100 * i / m_iicCmds.length()));
        }

        QThread::msleep(iicCmd.wait);

    }
}

void TlvCmdTask::runTlv()
{
    int i = 0;
    emit hasDone(0, 0);
    for (const TlvSend_t& tlvCmd : m_tlvCmds) {

        auto res = TlvThreadCom::instance()->syncWrite(tlvCmd.tlv);
        if (res.isEmpty()) {  // 超时了
            stop();
        } else {
            emit hasDone(i, (int)(100 * i / m_tlvCmds.length()));
        }

        QThread::msleep(tlvCmd.wait);
    }
}

void TlvCmdTask::_run()
{
    if (m_isIIC) {
        runIIC();
    } else {
        runTlv();
    }
}

void TlvCmdTask::runTask()
{
    while (!m_requestStop) {
        if (m_runCnt == 0) {
            m_requestStop = true;
            break;
        }
        if (m_runCnt > 0) m_runCnt--;
        _run();
    }
    m_requestStop = false;
}
